<?php

namespace App\Http\Controllers\backend;

use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Input;
use App\Models\Administrator;
use Illuminate\Support\Facades\Hash;

class AdministratorController extends BaseController {
	
	public function index() {
		$administrators = Administrator::orderBy('order')->get();
		return view('backend.administrators', compact('administrators'));
	}
	
	public function create() {
		$administrator = new Administrator();
		return view('backend.administrator_form', compact('administrator'));
	}
	
	public function store() {
		$input = Input::all();
		$avatar = $input['avatar'];
		unset($input['avatar']);
		$validation = validator($input, Administrator::$rules, Administrator::$msgs);
		if($validation->passes()) {
			$input['password'] = Hash::make($input['password']);
			$administrator = Administrator::create($input);
			$avatar->move(public_path('uploads/images'), $administrator->id.'.jpg');
			$avatar = $administrator->id.'.jpg';
			$administrator->avatar = $avatar;
			$administrator->save();
			return redirect('backend/administrators');
		}
		return Redirect::back()
				->withInput()
				->withErrors($validation);
	}
	
	public function edit($id) {
		$administrator = Administrator::find($id);
		return view('backend.administrator_form', compact('administrator'));
	}
	
	public function update($id) {
		$input = Input::all();
		$administrator = Administrator::find($id);
		$rules = [
			'nickname' => 'required',
			'cellphone' => 'required',
		];
		if(empty($input['password'])) {
			unset($input['password']);
		}
		$validation = validator($input, $rules, Administrator::$msgs);
		if($validation->passes()) {
			if(isset($input['avatar'])) {
				if($administrator->avatar != 'nocover.jpg') {
					@unlink(public_path('uploads/images/'. $administrator->avatar ));
				}
				$input['avatar']->move(public_path('uploads/images'), $administrator->id.'.jpg');
				$input['avatar'] = $administrator->id.'.jpg';
			}
			$administrator->update($input);
			$administrator->save();
			return redirect('backend/administrators');
		}
		return Redirect::back()
				->withInput()
				->withErrors($validation);
	}
	
	public function destroy($id) {
		$administrator = Administrator::find($id);
		if($administrator->avatar != 'nocover.jpg') {
			@unlink(public_path('uploads/avatar/'. $administrator->avatar ));
		}
		$administrator->delete();
		return redirect('backend/administrators');
	}
}
